<template>
  <div>
    <!-- 搜速区 -->
    <div class="search">
      <label style="color: #666; font-size: 12px">客房类型：</label>
      <el-select
        size="mini"
        v-model="roomTypeId"
        placeholder="请选择类型"
        clearable
        style="margin-right: 10px; width: 130px"
      >
        <el-option
          v-for="item in roomTypeSearchList"
          :key="item.roomTypeId"
          :label="item.roomTypeName"
          :value="item.roomTypeId"
        >
        </el-option>
      </el-select>
      <label style="color: #666; font-size: 12px">客房状态：</label>
      <el-select
        size="mini"
        v-model="roomStateId"
        placeholder="请选择状态"
        clearable
        style="margin-right: 10px; width: 130px"
      >
        <el-option
          v-for="item in roomStateSearchList"
          :key="item.roomStateId"
          :label="item.roomStateName"
          :value="item.roomStateId"
        >
        </el-option>
      </el-select>
      <el-button
        type="primary"
        icon="el-icon-search"
        size="small"
        @click="searchClick"
      ></el-button>
      <el-button
        type="primary"
        icon="el-icon-document-add"
        size="small"
        @click="addClick"
      ></el-button>
      <el-button
        type="success"
        icon="el-icon-share"
        size="small"
        @click="excelClick"
      ></el-button>
    </div>
    <!-- 表格 -->
    <el-table :data="tableData" style="width: 99.9%" size="mini">
      <el-table-column label="房间号" width="180">
        <template slot-scope="scope">
          {{ scope.row.roomId }}
        </template>
      </el-table-column>
      <el-table-column label="房间类型" width="180">
        <template slot-scope="scope">
          {{ scope.row.roomType.roomTypeName }}
        </template>
      </el-table-column>
      <el-table-column label="床位数" width="180">
        <template slot-scope="scope">
          {{ scope.row.roomType.bedNum }}
        </template>
      </el-table-column>
      <el-table-column label="价格" width="180">
        <template slot-scope="scope">
          {{ scope.row.roomType.roomTypePrice }}
        </template>
      </el-table-column>
      <el-table-column label="房间状态" width="180">
        <template slot-scope="scope">
          <el-tag
            size="small"
            :type="
              scope.row.roomStateId === 1
                ? 'success'
                : scope.row.roomStateId === 2
                ? 'danger'
                : 'warning'
            "
            disable-transitions
            >{{ scope.row.roomState.roomStateName }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="房间图片" width="180">
        <template slot-scope="scope">
          <el-image
            style="width: 65px; height: 65px"
            :src="
              BASE_URL_RoomImg +
              (scope.row.roomImgName
                ? scope.row.roomImgName
                : 'roomType_default.jpg')
            "
            fit="cover"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="warning"
            @click="handleEdit(scope.$index, scope.row)"
            ><i class="el-icon-edit-outline"></i
          ></el-button>
          <el-button
            size="mini"
            type="primary"
            @click="handleShowImg(scope.$index, scope.row)"
            ><i class="el-icon-picture-outline"></i
          ></el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            ><i class="el-icon-delete"></i
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="flex j-c" style="margin-top: 10px">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="count"
        :page-size="6"
        hide-on-single-page
        @current-change="currentChange"
      >
      </el-pagination>
    </div>
    <!-- 添加抽屉 -->
    <el-drawer
      :title="isAdd ? '添加客房' : '修改客房'"
      :visible.sync="drawer"
      direction="rtl"
      :before-close="drawerClose"
      size="40%"
      :wrapperClosable="false"
    >
      <div style="padding: 0 15px">
        <el-form
          size="mini"
          :model="ruleForm"
          status-icon
          :rules="rules"
          ref="ruleForm"
          label-width="75px"
          class="demo-ruleForm"
        >
          <el-form-item label="房间号" prop="roomId">
            <el-input
              type="text"
              v-model="ruleForm.roomId"
              autocomplete="off"
              style="width: 150px"
            ></el-input>
          </el-form-item>
          <el-form-item label="房间类型" prop="roomTypeId">
            <el-select
              size="mini"
              v-model="ruleForm.roomTypeId"
              placeholder="请选择类型"
              clearable
              style="margin-right: 10px; width: 130px"
            >
              <el-option
                v-for="item in roomTypeList"
                :key="item.roomTypeId"
                :label="item.roomTypeName"
                :value="item.roomTypeId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="房间状态" prop="roomStateId">
            <el-select
              size="mini"
              v-model="ruleForm.roomStateId"
              placeholder="请选择状态"
              clearable
              style="margin-right: 10px; width: 130px"
              :disabled="ruleForm.roomStateId === 2 ? true : false"
            >
              <el-option
                v-for="item in roomStateList"
                :key="item.roomStateId"
                :label="item.roomStateName"
                :value="item.roomStateId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="房间描述" prop="roomDescription">
            <quill-editor
              v-model="ruleForm.roomDescription"
              ref="myQuillEditor"
              style="height: 300px; margin-bottom: 100px"
            >
            </quill-editor>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">{{
              isAdd ? "添加" : "修改"
            }}</el-button>
            <el-button @click="resetForm('ruleForm')">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
    <!-- 图片弹出层 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-upload
        :action="UPLOAD_RoomImg_URL"
        list-type="picture-card"
        :file-list="fileList"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
      <!-- 嵌套弹出层显示大图 -->
      <el-dialog :visible.sync="dialogVisible2" append-to-body>
        <img width="100%" :src="dialogImageUrl" alt="" />
      </el-dialog>
    </el-dialog>
  </div>
</template>
<script>
// 导入图片根路径和上传路径
import {
  BASE_URL_RoomImg,
  UPLOAD_RoomImg_URL,
  BASE_URL_RoomTypeImg,
} from "../../config/index";
// 导入xlsx方法
import { xlsx } from "../../util/xlsx";
export default {
  data() {
    // 验证
    var validateRoomId = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入客房编号"));
      } else {
        callback();
      }
    };
    var validateRoomStateId = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择客房状态"));
      } else {
        callback();
      }
    };
    var validateRoomTypeId = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择客房类型"));
      } else {
        callback();
      }
    };
    return {
      // 是否显示弹出层
      dialogVisible: false,
      // 用于预览图片弹出层
      dialogVisible2: false,
      // 弹出层预览图的地址
      dialogImageUrl: "",
      // 定义房间图片对应的房间号
      roomId: "",
      // 定义房间照片显示的数组
      fileList: [],
      // 表格数据
      tableData: [],
      // 表格数据的总数量
      count: 0,
      // 当前页
      pageIndex: 1,
      // 客房类型编号
      roomTypeId: "",
      // 客房状态编号
      roomStateId: "",
      // 搜索区域的客房类型列表(用于查询)
      roomTypeSearchList: [],
      // 客房类型列表(用于添加)
      roomTypeList: [],
      // 搜索区域的房状态列表(用于查询)
      roomStateSearchList: [],
      // 客房状态列表(用于添加)
      roomStateList: [],
      // 用于备份添加时的数据
      roomStateList1: [],
      // 用于修改
      roomStateList2: [],
      BASE_URL_RoomTypeImg,
      // 房间类型图片根路径
      BASE_URL_RoomImg,
      // 管理员头像上传路径
      UPLOAD_RoomImg_URL,
      // 是否做添加操作
      isAdd: true,
      // 是否打开抽屉
      drawer: false,
      //表单数据
      ruleForm: {
        // 房间号
        roomId: "",
        // 状态编号
        roomStateId: "",
        // 类型编号
        roomTypeId: "",
        // 房间描述
        roomDescription: "",
      },
      // 表单验证数据
      rules: {
        // 验证
        roomId: [{ validator: validateRoomId, trigger: "blur" }],
        roomStateId: [{ validator: validateRoomStateId, trigger: "change" }],
        roomTypeId: [{ validator: validateRoomTypeId, trigger: "change" }],
      },
    };
  },
  created() {
    // 调用获取表格数据的方法
    this.getTableData();
    // 获取房间类型的方法
    this.getRoomTypeList();
    this.getRoomStateList();
  },
  methods: {
    // 获取表格数据
    async getTableData() {
      // 获取房间类型信息
      let res = await this.$get("/room/list", {
        roomTypeId: this.roomTypeId || 0,
        roomStateId: this.roomStateId || 0,
        pageIndex: this.pageIndex,
        pageSize: 6,
      });
      this.tableData = res.data.list;
      // 设置总数量
      this.count = res.data.total;
    },
    // 获取客房类型列表
    async getRoomTypeList() {
      let res = await this.$get("/roomType/list");
      this.roomTypeList = res.data;
      this.roomTypeSearchList = res.data;
    },
    // 获取客房状态列表
    async getRoomStateList() {
      let res = await this.$get("/roomState/list");
      this.roomStateSearchList = res.data;
      // 获取添加时的房间状态信息(添加房间时没有入住)
      let res2 = await this.$get("/roomState/listForAdd");
      this.roomStateList = res2.data;
      // 保存一份添加时的数据
      this.roomStateList1 = res2.data;
      console.log(this.roomStateList);
      let res3 = await this.$get("/roomState/listForUpdate");
      this.roomStateList2 = res3.data;
      console.log(this.roomStateList2);
    },
    // 分页方法
    currentChange(pageIndex) {
      // 设置当前页码
      this.pageIndex = pageIndex;
      // 重新调用获取表格数据的方法
      this.getTableData();
    },
    async handleEdit(index, row) {
      // 获取房间编号
      let roomId = row.roomId;
      // 根据房间编号获取对象
      let res = await this.$get("/room/getOne", { roomId });
      this.ruleForm = res.data;
      // 给表单对象添加一个id,用于保存原始房间号,便于修改
      this.ruleForm.id = res.data.roomId;
      this.roomStateList = this.roomStateList2;
      // 如果房间是空闲状态,在修改时需要除去已入住的状态
      if (this.ruleForm.roomStateId != 2) {
        this.roomStateList = this.roomStateList.filter(
          (obj) => obj.roomStateId != 2
        );
      }
      // 表示这是修改操作
      this.isAdd = false;
      // 打开抽屉
      this.drawer = true;
    },
    // 查看客房图片
    handleShowImg(index, row) {
      this.dialogVisible = true;
      // 获取客房编号
      this.roomId = row.roomId;
      // 显示图片
      this.showImgList();
    },
    // 获取图片列表的方法
    async showImgList() {
      // 根据客房编号查询所有的客房图片
      let { data } = await this.$get("/roomImg/list", {
        roomId: this.roomId,
      });
      if (data != null) {
        // 设置照片详情上的照片列表
        this.fileList = data.map((r) => {
          return {
            roomImgId: r.roomImgId,
            name: r.roomImgName,
            url: this.BASE_URL_RoomImg + r.roomImgName,
          };
        });
      }
    },
    // 关闭图片弹出框
    handleClose(done) {
      // 清空照片墙上的缓存的房间照片
      this.fileList = [];
      done();
    },
    // 删除照片墙里的照片
    async handleRemove(file, fileList) {
      let { roomImgId, name } = file;
      // 删除对应图片的信息
      let { success, message } = await this.$post("/roomImg/delete", {
        roomImgId,
        fileName: name,
      });
      if (success) {
        this.fileList.pop({
          roomImgId: roomImgId,
          name: name,
          url: this.BASE_URL_RoomImg + name,
        });
        this.$message({
          showClose: true,
          message: message,
          type: "success",
          duration: 1200,
        });
      } else {
        this.$message({
          showClose: true,
          message: message,
          type: "error",
          duration: 1200,
        });
      }
    },
    handlePictureCardPreview(file) {
      // 设置显示大图的地址
      this.dialogImageUrl = file.url;
      this.dialogVisible2 = true;
    },
    // 上传成功
    async handleAvatarSuccess(res) {
      // 表示图片上传到服务器成功,未保存到数据库
      if (res.success) {
        // 添加客房图片到该房间中(将图片添加到数据库中)
        let { success, message, data } = await this.$post("/roomImg/add", {
          roomId: this.roomId,
          roomImgName: res.data,
        });
        if (success) {
          // this.showImgList();
          // 向fileList数组中添加这条图片信息;
          this.fileList.push({
            roomImgId: data,
            name: res.data,
            url: this.BASE_URL_RoomImg + res.data,
          });
          this.$message({
            showClose: true,
            message: message,
            type: "success",
            duration: 1500,
          });
        } else {
          this.$message({
            showClose: true,
            message: message,
            type: "error",
            duration: 1500,
          });
        }
      }
    },
    // 上传之前
    beforeAvatarUpload(file) {
      // 定义可以上传的图片格式
      let imgTypeList = ["image/jpeg", "image/png", "image/gif"];
      const isType = imgTypeList.includes(file.type);
      const isLt4M = file.size / 1024 / 1024 <= 4;

      if (!isType) {
        this.$message.error("上传客房图片只能是 JPG PNG GIF 格式!");
      }
      if (!isLt4M) {
        this.$message.error("上传客房图片大小不能超过 4MB!");
      }
      return isType && isLt4M;
    },
    async handleDelete(index, row) {
      await this.$con_f("是否确定删除?");
      let roomId = row.roomId;
      // 删除对应的角色信息
      let { success, message } = await this.$post("/room/delete", {
        roomId,
      });
      if (success) {
        this.$message({
          showClose: true,
          message: message,
          type: "success",
          duration: 1500,
        });
        // 获取最新数据
        this.getTableData();
      } else {
        this.$message({
          showClose: true,
          message: message,
          type: "error",
          duration: 1500,
        });
      }
    },
    // 添加按钮点击方法
    addClick() {
      this.drawer = true;
      this.roomStateList = this.roomStateList1;
    },
    searchClick() {
      this.getTableData();
    },
    // 导出Excel表的方法
    excelClick() {
      // 组织导出的数据
      let json = this.tableData.map((r) => {
        return {
          roomId: r.roomId,
          roomType: r.roomType.roomTypeName,
          bedNum: r.roomType.bedNum,
          price: r.roomType.roomTypePrice,
          roomState: r.roomState.roomStateName,
        };
      });
      // 组织表头对象
      let fields = {
        roomId: "房间编号",
        roomType: "房间类型",
        bedNum: "床位数",
        price: "价格",
        roomState: "客房状态",
      };
      // 定义文件名称
      let fileName = "客房信息表";
      xlsx(json, fields, fileName);
    },
    // 关闭抽屉
    drawerClose(done) {
      // 清空表单数据
      this.resetForm("ruleForm");
      // 表单恢复成默认状态
      this.isAdd = true;
      done();
    },
    // 表单提交方法
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        // 判断表单数据是否验证成功
        if (valid) {
          if (this.isAdd) {
            // 执行添加功能
            let { success, message } = await this.$post(
              "/room/add",
              this.ruleForm
            );
            // 判断是否添加成功
            if (success) {
              this.$message({
                showClose: true,
                message: message,
                type: "success",
                duration: 1500,
              });
              // 清空表单
              this.resetForm("ruleForm");
              // 关闭抽屉
              this.drawer = false;
              // 获取最新数据
              this.getTableData();
            } else {
              this.$message({
                showClose: true,
                message: message,
                type: "error",
                duration: 1500,
              });
            }
          } else {
            // 执行修改操作
            let { success, message } = await this.$post(
              "/room/update",
              this.ruleForm
            );
            // 判断是否修改成功
            if (success) {
              this.$message({
                showClose: true,
                message: message,
                type: "success",
                duration: 1500,
              });
              this.drawer = false;
              // 获取最新数据
              this.getTableData();
            } else {
              this.$message({
                showClose: true,
                message: message,
                type: "error",
                duration: 1500,
              });
            }
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 表单重置方法
    resetForm(formName) {
      this.$refs[formName].resetFields();
      // 清空数据
      this.ruleForm = {
        // 房间号
        roomId: "",
        // 状态编号
        roomStateId: "",
        // 类型编号
        roomTypeId: "",
        // 房间描述
        roomDescription: "",
      };
    },
  },
};
</script>
<style scoped lang='scss'>
.search {
  padding: 4px 10px;
}
</style>